import serial
import time


class RadarSensor:
    def __init__(self, port, baudrate=256000):
        self.ser = serial.Serial(
            port=port,
            baudrate=baudrate,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1
        )

    def get_angle(self):
        if self.ser.in_waiting > 0:
            data = self.ser.readline().decode('utf-8').strip()
            parts = data.split(',')
            return parts[0] if len(parts) > 0 else '0'
        return '0'

    def get_speed(self):
        if self.ser.in_waiting > 0:
            data = self.ser.readline().decode('utf-8').strip()
            parts = data.split(',')
            return parts[1] if len(parts) > 1 else '0'
        return '0'

    def get_distance(self):
        if self.ser.in_waiting > 0:
            data = self.ser.readline().decode('utf-8').strip()
            parts = data.split(',')
            return parts[2] if len(parts) > 2 else '0'
        return '0'

    def read_data(self):
        while True:
            if self.ser.in_waiting > 0:
                data = self.ser.readline()
                print("Received:", data.decode('utf-8').strip())
                # 可以添加解析数据的代码
            time.sleep(0.1)

    def close(self):
        self.ser.close()
